package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {
    private Connection connection;
    Properties prop = new Properties();
    InputStream input = null;


    public Connection getconnection() {

//        String url = "jdbc:mysql://localhost:3306/user";
//        String username = "root";
//        String password = "123456";

        // 从 properties 中获取数据库连接信息
//        String url = prop.getProperty("url");
//        String username = prop.getProperty("username");
//        String password = prop.getProperty("password");

        try {
            //导入properties
//            String filePath = "src/main/resources/jdbc.properties";
//            FileInputStream input = new FileInputStream(filePath);
            System.out.println("Current working directory: " + new File(".").getAbsoluteFile());


            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                System.out.println("jdbc.properties not found inside the jar");
            }

            prop.load(inputStream);

            String url = prop.getProperty("url");
            String username = prop.getProperty("username");
            String password = prop.getProperty("password");

            // 1.加载数据库驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            System.out.println("驱动连接成功！");
            if(connection==null||connection.isClosed()) {
                //2.创建connection 进行连接，参数：url，username，password
                //        String url = "jdbc:mysql://localhost:3306/user";
                //        String username = "root";
                //        String password = "123456";

                connection = DriverManager.getConnection(url, username, password);
                return connection;
            }

        } catch (ClassNotFoundException | SQLException | IOException e ) {
            System.out.println("驱动连接失败！");
            throw new RuntimeException(e);
        }
        return connection;
    }

//    //创建一个预编译的 SQL 语句（PreparedStatement）
//    public PreparedStatement prepareStatement(String sql) throws SQLException {
//        if (connection == null || connection.isClosed()) {
//            throw new IllegalStateException("数据库连接未初始化或已关闭");
//        }
//        return connection.prepareStatement(sql);
//    }


//变长参数更新  params-参数  对已存储数据进行更新，参数不固定
public boolean paramsUpdate1(String sql, Object... params) {
    getconnection();
    PreparedStatement preparedStatement = null;

    try {

        preparedStatement = connection.prepareStatement(sql); // 准备 SQL 语句

        // 设置参数
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        // 执行更新操作，并获取影响行数
        int rowsAffected = preparedStatement.executeUpdate();

        // 返回更新是否成功
        return rowsAffected > 0;
    } catch (SQLException e) {
        e.printStackTrace(); // 打印异常信息
        return false; // 更新操作失败
    } finally {
        // 关闭 PreparedStatement
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 关闭 Connection
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

    public boolean paramsUpdate2(String sql, Object... params) {
        getconnection();
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
            // 执行更新操作
            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0; // 返回更新行数是否大于0，表示更新成功
        } catch (SQLException e) {
            e.printStackTrace(); // 可以将异常信息打印出来，便于调试
            return false; // 更新操作失败
        } finally {
            // 在 finally 块中确保关闭数据库连接
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public boolean paramsUpdate(String sql, Object... params) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = getconnection();
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
            // 执行更新操作
            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0; // 返回更新行数是否大于0，表示更新成功
        } catch (SQLException e) {
            e.printStackTrace(); // 打印异常信息
            return false; // 更新操作失败
        } finally {
            // 关闭资源
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //变长 sql 查询
    public ResultSet prepareQuery(String sql, Object... params) {
      connection= getconnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }

            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
            return null; // or throw an exception
        }
    }
//关闭
    public void closeConnection(){
        try{
            if(connection!=null&&!connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            System.out.println("关闭失败！");
        }
    }


    public PreparedStatement prepareStatement(String sql) throws SQLException {
        if (connection == null) {
            throw new SQLException("Connection is not initialized.");
        }
        return connection.prepareStatement(sql);
    }
}
